/*
 * Unicode.cpp
 *
 *  Created on: 2012-12-7
 *      Author: yangentao@gmail.com
 */

#include "Unicode.h"
#include <windows.h>
#include <assert.h>
namespace yet {

wstring decode(UINT codePage, const char* text, int length) {
	assert(length ==-1 || length >0);
	wstring result;
	int len = MultiByteToWideChar(codePage, 0, text, length, 0, 0);
	if (len > 0) {
		wchar_t* buf = new wchar_t[len];
		int n = MultiByteToWideChar(codePage, 0, text, length, buf, len);
		if (n > 0) {
			result = buf;
		}
		delete[] buf;
	}
	return result;
}
string encode(UINT codePage, const wchar_t* text, int length) {
	assert(length ==-1 || length >0);
	string result;
	BOOL useDefaultChar = FALSE;
	int len = WideCharToMultiByte(codePage, 0, text, length, 0, 0, 0, 0);
	if (len > 0) {
		char* buf = new char[len];
		int n = WideCharToMultiByte(codePage, 0, text, length, buf, len, 0, 0);
		if (n > 0) {
			result = buf;
		}
		delete[] buf;
	}
	return result;
}
wstring decodeUtf8(const char* text, int length) {
	return decode(CP_UTF8, text, length);
}
string encodeUtf8(const wchar_t* text, int length) {
	return encode(CP_UTF8, text, length);
}
wstring decodeACP(const char* text, int length) {
	return decode(CP_ACP, text, length);
}
string encodeACP(const wchar_t* text, int length) {
	return encode(CP_ACP, text, length);
}
} /* namespace yet */
